<template>
    <div class="app-container">
        <el-row :gutter="10">
            <el-col :span="5">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <h3>文档基本信息</h3>
                        <el-divider></el-divider>
                    </div>
                    <el-form label-position="top" label-width="100px">
                        <el-form-item label="文档标题">
                            <span>{{ document.name }}</span>
                        </el-form-item>
                        <el-form-item label="文档编号">
                            <span>{{ document.id }}</span>
                        </el-form-item>
                        <el-form-item label="文件类型">
                            <span>{{ document.fileType }}</span>
                        </el-form-item>
                        <el-form-item label="文件大小">
                            <span>{{ document.fileSize }} Kb</span>
                        </el-form-item>
                        <el-form-item label="文件路径">
                            <span>{{ document.filePath }}</span>
                        </el-form-item>
                        <el-form-item label="存放位置">
                            <span>{{ document.fileLocation }}</span>
                        </el-form-item>
                        <el-form-item label="创建人">
                            <span>{{ document.createBy }}</span>
                        </el-form-item>
                        <el-form-item label="创建时间">
                            <span>{{ document.createTime }}</span>
                        </el-form-item>
                        <el-form-item label="更新人">
                            <span>{{ document.updateBy }}</span>
                        </el-form-item>
                        <el-form-item label="更新时间">
                            <span>{{ document.updateTime }}</span>
                        </el-form-item>
                        <el-form-item label="备注">
                            <span>{{ document.remark }}</span>
                        </el-form-item>
                        <el-form-item label="额外信息">
                            <el-button type="primary" @click="showExtraInfo()">点击查看</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="19">
                <el-card class="box-card">
                    <el-watermark :content="watermarkContent" :font="config.font" :rotate="config.rotate"
                        :gap="config.gap" :offset="config.offset">
                        <div class="media-container">
                            <!-- PDF 文件 -->
                            <div v-if="isPDF" class="pdf-container">
                                <iframe :src="mediaUrl" :headers="headers" width="100%" height="100%"
                                    frameborder="0"></iframe>
                            </div>

                            <!-- 视频文件 -->
                            <video-player v-else-if="isVideo" :src="mediaUrl" :poster="videoPoster" controls
                                class="video-player" />

                            <!-- 音频文件 -->
                            <audio-player v-else-if="isAudio" :src="mediaUrl" controls class="audio-player" />

                            <!-- 其他文件类型提示 -->
                            <div v-else class="unsupported-file">
                                <el-alert title="不支持的文件类型" type="warning" :closable="false" show-icon>
                                    <p>系统暂不支持预览该类型文件，请下载后查看</p>
                                </el-alert>
                            </div>
                        </div>
                    </el-watermark>
                </el-card>
            </el-col>
        </el-row>

        <el-dialog title="额外信息" v-model="extraInfoDialog" width="500px" append-to-body
            class="enhanced-extra-info-dialog">
            <div class="enhanced-extra-info-container">
                <el-scrollbar max-height="400px">
                    <div v-for="(item, index) in extraInfo" :key="index" class="enhanced-extra-info-item"
                        :class="{ 'last-item': index === extraInfo.length - 1 }">
                        <div class="info-label">
                            <el-tag type="info" size="small">{{ item.label }}</el-tag>
                        </div>
                        <div v-html="DOMPurify.sanitize(item.value)" class="info-content"></div>
                    </div>
                </el-scrollbar>
            </div>

            <template #footer>
                <div class="enhanced-dialog-footer">
                    <el-button @click="extraInfoDialog = false" type="primary" size="small">
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getDocument } from '@/api/manage/document'
import { getToken } from "@/utils/auth";
import axios from 'axios'
import { color } from 'echarts';
import { getDefaultWatermark } from '@/api/manage/watermark'
import { getUserProfile } from "@/api/system/user";
import DOMPurify from 'dompurify'
import { forceLogout, list as initData } from "@/api/monitor/online";
import VideoPlayer from '@/components/Player/VideoPlayer'
import AudioPlayer from '@/components/Player/AudioPlayer'

const { proxy } = getCurrentInstance()
const headers = ref({ Authorization: "Bearer " + getToken() });
const data = reactive({
    config: {
        content: '智慧档案管理系统',
        font: {
            fontSize: 16,
            color: 'rgba(0, 0, 0, 0.15)',
            fontFamily: 'sans-serif',
            fontStyle: 'normal',
            fontWeight: 'normal',
        },
        rotate: -22,
        gap: [100, 100],
        offset: [50, 50],
    },
})
const { config } = toRefs(data)

// 获取当前时间戳：年-月-日 时:分:秒 的格式
const nowDate = new Date().toLocaleString()
// 水印内容
const watermarkContent = ref("")

const documentId = ref(0)
const document = ref({})
const pdfUrl = ref('')
const extraInfoDialog = ref(false)
const extraInfo = ref([])
const user = ref({})
const onlineList = ref([]);

// 在原有代码基础上新增以下内容
const mediaUrl = ref('')
const isPDF = ref(false)
const isVideo = ref(false)
const isAudio = ref(false)
const videoPoster = ref('') // 视频封面图，可选

// 文件类型判断逻辑
const checkFileType = () => {
    const fileType = document.value.fileType?.toLowerCase()
    isPDF.value = fileType === 'pdf'
    isVideo.value = ['mp4', 'avi', 'mov', 'wmv'].includes(fileType)
    isAudio.value = ['mp3', 'wav', 'ogg'].includes(fileType)
}

// 获取媒体URL
const getMediaUrl = async () => {
    if (document.value.filePath.startsWith("http://127.0.0.1:8080")) {
        try {
            const response = await axios({
                url: document.value.filePath,
                method: 'GET',
                responseType: 'blob'
            })

            const blob = new Blob([response.data], {
                type: `application/${document.value.fileType}`
            })

            mediaUrl.value = URL.createObjectURL(blob)
        } catch (error) {
            console.error('Error fetching media:', error)
        }
    } else {
        mediaUrl.value = document.value.filePath
    }
}

function getUser() {
    getUserProfile().then(response => {
        user.value = response.data;
        console.log("Current user:", user.value);
        watermarkContent.value = user.value.userName + document.value.name + " " + nowDate;
        initData({ userName: user.value.userName }).then(response => {
            onlineList.value = response.rows;
            console.log("onlineList", onlineList.value);
        });
    });
};


onMounted(() => {
    documentId.value = proxy.$route.query.id;

    getDocument(documentId.value).then(response => {
        document.value = response.data;
        getUser();

        checkFileType() // 新增类型判断
        getMediaUrl()  // 新增获取媒体URL

        // Fetch the PDF file and create a Blob URL
        // if (document.value.filePath.startsWith("http://127.0.0.1:8080")) {
        //     console.log("document.value.filePath", document.value.filePath);
        //     axios({
        //         url: document.value.filePath,
        //         method: 'GET',
        //         responseType: 'blob'
        //     }).then(response => {
        //         const blob = new Blob([response.data], { type: 'application/pdf' });
        //         pdfUrl.value = URL.createObjectURL(blob);
        //     }).catch(error => {
        //         console.error('Error fetching PDF:', error);
        //     });
        // } else {
        //     pdfUrl.value = document.value.filePath;
        // }
    })

    getDefaultWatermark().then(response => {
        if (response.code === 200) {
            // config.value.content = response.data.content;
            config.value.font.fontSize = response.data.fontsize;
            config.value.font.color = response.data.color;
            config.value.font.fontFamily = response.data.fontfamily;
            config.value.font.fontStyle = response.data.fontstyle;
            config.value.font.fontWeight = response.data.fontweight;
            config.value.rotate = response.data.rotate;
            config.value.gap[0] = response.data.gapX;
            config.value.gap[1] = response.data.gapY;
            config.value.offset[0] = response.data.offsetX;
            config.value.offset[1] = response.data.offsetY;
            // console.log("config:", config);
        }
    })
})

function showExtraInfo() {
    extraInfoDialog.value = true
    extraInfo.value = JSON.parse(document.value.extraInfo)
}
</script>

<style scoped>
/* 新增样式 */
.media-container {
    width: 100%;
    height: 900px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f5f7fa;
}

.video-player {
    width: 100%;
    height: 100%;
    max-width: 1200px;
    background: #000;
}

.audio-player {
    width: 80%;
    margin: 0 auto;
}

.unsupported-file {
    padding: 20px;
    text-align: center;
}

.pdf-container {
    width: 100%;
    height: 900px;
    overflow: auto;
}

.enhanced-extra-info-dialog {
    border-radius: 8px;
}

.enhanced-extra-info-container {
    padding: 0 10px;
}

.enhanced-extra-info-item {
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
}

.enhanced-extra-info-item.last-item {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.info-label {
    margin-bottom: 8px;
}

.info-content {
    padding-left: 8px;
    line-height: 1.6;
    color: #333;
}

.enhanced-dialog-footer {
    text-align: center;
    padding-top: 10px;
}
</style>